<?php
/**
 * Author panxu
 * Date   2019/8/9 16:02
 */

namespace App\HttpController;

use App\Utility\Pool\MysqlPool;
use App\Utility\Pool\RedisPool;
use EasySwoole\FastCache\Cache;
use function MongoDB\BSON\toJSON;

class Index extends Base
{


    function index()
    {
        $token = $this->request()->getRequestParam('token');
        if (empty($token)) {
            return $this->response()->redirect('login');
        }
        $redis = RedisPool::defer();
        if(!$redis->exists($token))
        {
            return $this->response()->redirect('login');
        }
        $ws = "ws://127.0.0.1:9501?token=".$token;
        return $this->render('index',compact('ws'));
    }


    function login()
    {
        if ($this->request()->getMethod() == "POST") {
            $username = $this->request()->getRequestParam('username');
            $password = $this->request()->getRequestParam('password');
            $db       = MysqlPool::defer();
            $info = $db->where('username', $username)->get('ch_user');
//            var_dump($info);
            if (empty($info)) {
                return $this->writeJson(201, [], "用户不存在");
            }
            if (!password_verify($password, $info[0]['password'])) {
                return $this->writeJson(201,[],"密码错误");
            }
            $token = uniqid().uniqid();
            $redis = RedisPool::defer();
            $redis->set($token,json_encode($info[0]));
            return $this->writeJson(200,['token'=>$token],'登陆成功');
        }
        return $this->render('login');
    }


    function logout()
    {
        $redis = RedisPool::defer();
        $redis->del($this->request()->getRequestParam('token'));
        $this->response()->redirect('/');
    }


    function find()
    {
        $key = $this->request()->getRequestParam('key');
        $db = MysqlPool::defer();
        $lists = [];
        if($key)
        {
            $lists = $db->where('username',"$key%",'like')->whereOr('id',$key)->get('ch_user');
        }

        return $this->render('find',compact('lists','key'));
    }


    function userinfo()
    {
        $token = $this->request()->getRequestParam('token');
        if (empty($token)) {
            return $this->wJson(-1,null,'token获取失败');
        }
        $redis = RedisPool::defer();
        $info = $redis->get($token);
        if(empty($info))
        {
            return $this->wJson(-1,null,'token失效');
        }
        $mine = json_decode($info,true);
        $db       = MysqlPool::defer();
        $newInfo = $db->where('id', $mine['id'])->get('ch_user');
        $db = MysqlPool::defer();
        $group = [];
        $friend = $db->get('ch_group');
        foreach ($friend as &$value)
        {
            $in = $db->where('my_uid',$mine['id'])->where('group_id',$value['id'])->get('ch_friend');
            $fids = array_column($in, 'friend_uid');
            $value['list'] = $fids ? $db->where('id',$fids,'in')->get('ch_user') : [];
        }
        $data = [
            'mine'=>$newInfo[0],
            'friend'=>$friend,
            'group'=>$group
        ];
        return $this->wJson(0,$data,'success');

    }


    function addfriend()
    {
        $token = $this->request()->getRequestParam('token');
        $fuid = $this->request()->getRequestParam('fuid');
        $msg = $this->request()->getRequestParam('msg');
        $group = $this->request()->getRequestParam('group');

        $redis = RedisPool::defer();
        $info = $redis->get($token);
        $mine = json_decode($info,true);
        $uid = $mine['id'];
        if($uid == $fuid){
            return $this->wJson(-1,null,'不能添加自己');
        }
        $db = MysqlPool::defer();
        $fri_record = $db->where('my_uid',$uid)->where('friend_uid',$fuid)->get('ch_friend');
        if($fri_record)
        {
            return $this->wJson(-1,null,'已经是你的好友了');
        }
        $ms_record = $db->where('uid',$uid)->where('fuid',$fuid)->where('status',0)->get('ch_friend_message');
        if($ms_record)
        {
            return $this->wJson(-1,null,'已发送，等待该用户回复中');
        }
        $username = $mine['username'];
        $avatar = $mine['avatar'];
        $data = [
            'uid'=>$uid,
            'fuid'=>$fuid,
            'content'=>json_encode(compact('uid','fuid','msg','group','username','avatar')),
            'type'=>1,
            'status'=>0
        ];
        $id = $db->insert('ch_friend_message',$data);

        if($id)
        {
            return $this->wJson(0,null,'请求成功');
        }else{
            return $this->wJson(-1,null,'请求失败,'.$db->getLastError());
        }


    }
    
    
    
    function msgbox()
    {
        $token = $this->request()->getRequestParam('token');
        $redis = RedisPool::defer();
        $info = $redis->get($token);
        $mine = json_decode($info,true);
        $uid = $mine['id'];
        $db = MysqlPool::defer();
        $fri_record = $db->where('fuid',$uid)->get('ch_off_message');
        foreach ($fri_record as &$value)
        {
            $value['content']= substr($value['content'],0,1) == '{' ? json_decode($value['content'],true) : $value['content'];
        }
        //标记离线消息为已读
        $db->where('fuid',$uid)->where('status',2)->update('ch_off_message',['status'=>1]);

        $date = date('Y年m月d日');
        $this->render('msgbox',compact('fri_record','date'));
    }

    //
    function agree()
    {
        $token = $this->request()->getRequestParam('token');
        $fuid = $this->request()->getRequestParam('uid');
        $group = $this->request()->getRequestParam('group');
        //token同意来自uid的好友请求
        $redis = RedisPool::defer();
        $info = $redis->get($token);
        $mine = json_decode($info,true);
        $uid = $mine['id'];
        $db = MysqlPool::defer();
        //标记消息
        $db->where('uid',$fuid)->where('fuid',$uid)->where('type',1)->where('handle',0)->update('ch_off_message',['handle'=>1]);
        $db->where('uid',$fuid)->where('fuid',$uid)->where('type',1)->where('status',0)->update('ch_friend_message',['status'=>1]);
        //加入好友
        //add
        $friendInfo =  $db->where('uid',$fuid)->where('fuid',$uid)->orderBy('id','desc')->getOne('ch_friend_message');
        $db->insert('ch_friend',[
            'my_uid'=>$fuid,
            'friend_uid'=>$uid,
            'group_id'=>json_decode($friendInfo['content'],true)['group'],
        ]);
        //accept
        $db->insert('ch_friend',[
            'my_uid'=>$uid,
            'friend_uid'=>$fuid,
            'group_id'=>$group,
        ]);
        $fuidInfo = $db->where('id',$fuid)->getOne('ch_user');
        $this->wJson(1,compact('fuidInfo'),'添加成功');

    }


    function test()
    {
        $db  = MysqlPool::defer();
        $res = $db->rawQuery('select version()');
        var_dump($res);
    }

    function test2()
    {
        $redis = RedisPool::defer();
        $redis->set('test', 'test', 600);
        var_dump($redis->get('test'));
    }

    function test3()
    {
        $token = $this->request()->getRequestParam('token');
        var_dump(Cache::getInstance()->get($token));
        var_dump(11);
    }

    function test4()
    {
        $this->render("websocket");
    }


    function onException(\Throwable $throwable): void
    {
//        var_dump($throwable->getMessage());
        $this->writeJson(201,[],$throwable->getMessage());
        
    }
}